using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class NoteSpawner : MonoBehaviour
{
    [Header("生成设置")]
    [SerializeField] private GameObject[] notePrefabs; // 不同类型的音符预制体
    [SerializeField] private Transform[] spawnPoints; // 不同高度的生成点
    [SerializeField] private float spawnRate = 1f; // 基础生成速率
    [SerializeField] private float minSpawnInterval = 0.3f; // 最小生成间隔
    
    [Header("难度设置")]
    [SerializeField] private float difficultyIncreaseRate = 0.05f; // 难度增加速率
    [SerializeField] private float maxDifficulty = 2f; // 最大难度倍率
    
    [Header("音乐同步")]
    [SerializeField] private bool useMusicSync = true; // 是否使用音乐同步
    [SerializeField] private float beatInterval = 0.5f; // 节拍间隔（秒）
    [SerializeField] private float beatOffset = 0f; // 节拍偏移
    
    // 音符生成控制
    private float nextSpawnTime = 0f;
    private float currentDifficulty = 1f;
    private bool isSpawning = true;
    private Coroutine spawnCoroutine;
    
    // 音符谱面数据
    [System.Serializable]
    public class NoteData
    {
        public float time; // 出现时间
        public int type; // 音符类型索引
        public int lane; // 音符轨道（高度）
    }
    
    [SerializeField] private List<NoteData> noteChart = new List<NoteData>(); // 预定义的音符谱面
    [SerializeField] private bool useNoteChart = false; // 是否使用预定义谱面
    
    private GameManager gameManager;
    
    private void Start()
    {
        gameManager = FindObjectOfType<GameManager>();
        
        if (useNoteChart)
        {
            // 使用预定义谱面生成音符
            StartCoroutine(SpawnNotesFromChart());
        }
        else
        {
            // 使用随机生成
            spawnCoroutine = StartCoroutine(SpawnNotesRoutine());
        }
    }
    
    // 随机生成音符的协程
    private IEnumerator SpawnNotesRoutine()
    {
        while (isSpawning)
        {
            if (gameManager != null && !gameManager.IsGameOver())
            {
                if (Time.time >= nextSpawnTime)
                {
                    SpawnRandomNote();
                    
                    // 计算下一次生成时间
                    float interval;
                    if (useMusicSync)
                    {
                        // 使用音乐节拍同步
                        float musicTime = gameManager.GetMusicTime();
                        float beatTime = beatInterval * currentDifficulty;
                        interval = beatTime - (musicTime % beatTime) + beatOffset;
                        if (interval < minSpawnInterval) interval += beatTime;
                    }
                    else
                    {
                        // 使用固定间隔
                        interval = spawnRate / currentDifficulty;
                        if (interval < minSpawnInterval) interval = minSpawnInterval;
                    }
                    
                    nextSpawnTime = Time.time + interval;
                    
                    // 随着时间增加难度
                    currentDifficulty += difficultyIncreaseRate * Time.deltaTime;
                    if (currentDifficulty > maxDifficulty) currentDifficulty = maxDifficulty;
                }
            }
            
            yield return null;
        }
    }
    
    // 从预定义谱面生成音符的协程
    private IEnumerator SpawnNotesFromChart()
    {
        float startTime = Time.time;
        
        foreach (NoteData note in noteChart)
        {
            // 等待直到达到音符的出现时间
            float waitTime = note.time - (Time.time - startTime);
            if (waitTime > 0)
            {
                yield return new WaitForSeconds(waitTime);
            }
            
            // 检查游戏是否结束
            if (gameManager != null && gameManager.IsGameOver())
            {
                break;
            }
            
            // 生成音符
            SpawnSpecificNote(note.type, note.lane);
        }
    }
    
    // 生成随机音符
    private void SpawnRandomNote()
    {
        if (notePrefabs.Length == 0 || spawnPoints.Length == 0) return;
        
        // 随机选择音符类型
        int noteIndex = Random.Range(0, notePrefabs.Length);
        
        // 随机选择生成位置
        int spawnPointIndex = Random.Range(0, spawnPoints.Length);
        
        // 实例化音符
        GameObject noteObj = Instantiate(
            notePrefabs[noteIndex],
            spawnPoints[spawnPointIndex].position,
            Quaternion.identity
        );
        
        // 可以在这里设置音符的其他属性
    }
    
    // 生成特定类型和位置的音符
    private void SpawnSpecificNote(int noteType, int lane)
    {
        if (notePrefabs.Length <= noteType || spawnPoints.Length <= lane) return;
        
        // 实例化音符
        GameObject noteObj = Instantiate(
            notePrefabs[noteType],
            spawnPoints[lane].position,
            Quaternion.identity
        );
        
        // 可以在这里设置音符的其他属性
    }
    
    // 停止生成音符
    public void StopSpawning()
    {
        isSpawning = false;
        
        if (spawnCoroutine != null)
        {
            StopCoroutine(spawnCoroutine);
        }
    }
    
    // 编辑器方法：添加音符到谱面
    public void AddNoteToChart(float time, int type, int lane)
    {
        NoteData newNote = new NoteData
        {
            time = time,
            type = type,
            lane = lane
        };
        
        noteChart.Add(newNote);
        
        // 按时间排序
        noteChart.Sort((a, b) => a.time.CompareTo(b.time));
    }
    
    // 编辑器方法：清空谱面
    public void ClearNoteChart()
    {
        noteChart.Clear();
    }
}